package com.sijia.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sijia.reggie.comment.R;
import com.sijia.reggie.dto.DishDto;
import com.sijia.reggie.entity.Dish;
import com.sijia.reggie.entity.DishFlavor;
import com.sijia.reggie.mapper.DishMapper;
import com.sijia.reggie.service.DishFlavorService;
import com.sijia.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 杨思佳
 * @version 1.0
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dm;

    @Autowired
    private DishFlavorService dfs;

    @Override
    public List<Dish> selectByIds(List<Long> ids) {
        return dm.selectByIds(ids);
    }

    /**
     * 新增菜品，更新dish和dish_flavor两张表
     *
     * @param dishDto
     * @return
     */
    @Transactional
    @Override
    public R<String> saveTwo(DishDto dishDto) {
        this.save(dishDto);//dishDto继承dish，save方法在调用时只会使用dish部分的数据，因此没有抛出异常
        Long dishId = dishDto.getId();
        for (DishFlavor ds : dishDto.getFlavors()) {
            ds.setDishId(dishId);
        }
        dfs.saveBatch(dishDto.getFlavors());
        return R.success("菜品添加成功");
    }

    @Transactional
    @Override
    public R<DishDto> getTwo(Long id) {
        Dish d = this.getById(id);
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dfs.list(wrapper);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(d, dishDto);
        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    @Override
    public R<String> updateTwo(DishDto dishDto) {
        this.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dfs.remove(queryWrapper);
        Long dishId = dishDto.getId();
        for (DishFlavor ds : dishDto.getFlavors()) {
            ds.setDishId(dishId);
        }
        dfs.saveBatch(dishDto.getFlavors());
        return R.success("更新成功");
    }
}
